package v1

import (
	"context"

	"wxpay/internal/service"
	wxpay "wxpay/pkg/api/v1"
	"wxpay/pkg/merrors"

	mchApi "wxpay/pkg/wechat_api"
)

// 查询结算账号 get /api/v1/wxpay/mch/settle-account
func (s *Server) SettlementAccountQuery(ctx context.Context, req *wxpay.SettlementAccountQueryRequest) (*wxpay.SettlementAccountQueryResponse, error) {
	const op merrors.Op = "SettlementAccountQuery"
	mchService := service.NewMchService(s.d)
	apiClient, err := mchService.BuildMchApiClient(ctx, req.MchId)
	if err != nil {
		return nil, err
	}
	resp, err := apiClient.SettlementQuery(ctx, mchApi.QuerySettlementRequest{SubMchID: req.SubMchId})
	if err != nil {
		return nil, merrors.E(op, merrors.Invalid, merrors.ErrWxApi, err)
	}
	return &wxpay.SettlementAccountQueryResponse{
		AccountType:   resp.AccountType,
		AccountBank:   resp.AccountBank,
		BankName:      resp.BankName,
		BankBranchId:  resp.BankBranchID,
		AccountNumber: resp.AccountNumber,
		VerifyResult:  resp.VerifyResult,
	}, nil
}

// 修改结算账号 post /api/v1/wxpay/mch/settle-account
func (s *Server) SettlementAccountModify(ctx context.Context, req *wxpay.SettlementAccountModifyRequest) (*wxpay.OperationResult, error) {
	const op merrors.Op = "SettlementAccountModify"
	mchService := service.NewMchService(s.d)
	apiClient, err := mchService.BuildMchApiClient(ctx, req.MchId)
	if err != nil {
		return nil, err
	}
	err = apiClient.SettlementModify(ctx, mchApi.ModifySettlementRequest{
		SubMchID:        req.SubMchId,
		AccountType:     req.AccountType,
		AccountBank:     req.AccountBank,
		BankAddressCode: req.BankAddressCode,
		BankName:        req.BankName,
		BankBranchID:    req.BankBranchId,
		AccountNumber:   req.AccountNumber,
	})
	if err != nil {
		return nil, merrors.E(op, merrors.Invalid, merrors.ErrWxApi, err)
	}
	return &wxpay.OperationResult{Message: "SUCCESS"}, nil
}

// 查询二级商户账户实时余额 GET /api/v1/wxpay/mch/balance/{sub_mch_id}
func (s *Server) SubMchAccountBalanceQuery(ctx context.Context, req *wxpay.SubMchAccountBalanceQueryRequest) (*wxpay.SubMchAccountBalanceQueryResponse, error) {
	const op merrors.Op = "SubMchAccountBalanceQuery"
	client, err := service.NewMchService(s.d).BuildMchApiClient(ctx, req.MchId)
	if err != nil {
		return nil, err
	}
	resp, err := client.SubMchBalanceQuery(ctx, mchApi.SubMchBalanceQueryRequest{
		SubMchID:    req.SubMchId,
		AccountType: req.AccountType.String(),
	})
	if err != nil {
		return nil, merrors.E(op, merrors.Invalid, merrors.ErrWxApi, err)
	}
	var accountType wxpay.MchAccountType
	switch resp.AccountType {
	case "BASIC":
		accountType = wxpay.MchAccountType_BASIC
	case "OPERATION":
		accountType = wxpay.MchAccountType_OPERATION
	case "FEES":
		accountType = wxpay.MchAccountType_FEES
	}
	return &wxpay.SubMchAccountBalanceQueryResponse{
		SubMchId:        resp.SubMchID,
		AccountType:     accountType,
		AvailableAmount: resp.AvailableAmount,
		PendingAmount:   resp.PendingAmount,
	}, nil
}
